import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token');
  const isAdminPath = request.nextUrl.pathname.startsWith('/admin');
  const isLoginPath = request.nextUrl.pathname === '/login';

  // 如果是管理员路径但没有token，重定向到登录页
  if (isAdminPath && !token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // 如果已登录但访问登录页，重定向到控制台
  if (isLoginPath && token) {
    return NextResponse.redirect(new URL('/admin/dashboard', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/admin/:path*', '/login'],
}; 